package org.jvm.thread;

import com.sun.xml.internal.fastinfoset.sax.Features;

import java.util.Map;
import java.util.Vector;
import java.util.concurrent.*;

public class OneByOneTest {
    private  static Vector printList = new Vector();
    private  static Vector askNetList = new Vector();
    private static ConcurrentLinkedQueue<String> concurrentLinkedQueue = new ConcurrentLinkedQueue<String>();//执行打印队列
    private  static Map<String, Future> featureMap = new ConcurrentHashMap<>();
    static ThreadPoolExecutor   threadPoolExecutor = new ThreadPoolExecutor(24, 24,  15000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());

    public static void main(String[] args) throws  Exception{
        //多线程发送获取面单请求，单线程打印。。
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //获取
                    if (!concurrentLinkedQueue.isEmpty()){
                     String nextPrintKey=   concurrentLinkedQueue.peek();
                     if (nextPrintKey!=null&&!nextPrintKey.trim().isEmpty()){
                         Future future= featureMap.get(nextPrintKey);
                         if (future!=null){
                             try {
                               String  expressNo= (String) future.get();
                                 //开始打印
                                 printString(expressNo);
                             }catch (Exception e){
                                 e.printStackTrace();
                             }
                           concurrentLinkedQueue.poll();//移除队列
                           featureMap.remove(nextPrintKey);//移除队列
                         }

                     }
                    }

                }
            }
        }).start();
        for (int i=0;i<50;i++){
         final    int tt=i;
            askNetList.add(tt+"装箱单id====");
            concurrentLinkedQueue.add(tt+"装箱单id====");
            Future<String> future =  threadPoolExecutor.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    String result =getExpressNo(tt+"装箱单id====");
                    System.out.println("获取面单成功===="+tt+"装箱单id====");
                    return  result;
                }
            });
            featureMap.put(tt+"装箱单id====",future);
        }

    }


    /**
     * 根据装箱id 获取面单及打印数据
     * @param boxid
     */
    public  static  String getExpressNo(String boxid)  {
        try {
            Thread.sleep((int)(1+Math.random()*(2000-1+1)));
        }catch (Exception e){
            e.printStackTrace();
        }

        return  boxid;

    }

    /**
     * 根据装箱id 获取面单及打印数据
     * @param boxid
     */
    public  static  void printString(String boxid) throws  Exception{

//        Thread.sleep((int)(1+Math.random()*(2000-1+1)));
        System.out.println("开始打印===="+boxid);
          printList.add(boxid);

    }
}
